// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { game } from "../../../../script/game/control/game";
import { cardBase, ItemBase } from "../../../../script/game/control/Item/ItemBase";
import { cardType, itemType, questionType } from "../../../../script/game/gameType";
import { ccs } from "../../../../script/util/services";
import { WinBase } from "../../../../script/wins/WinBase";

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends WinBase {

    item: questionType[] = [];
    cardType: cardType;

    score: number = 0;
    time: number = 0; //总时间
    leftTime: number = 10; //剩余时间
    curIndex: number = 0; //当前题目
    timer: number = 0; //计时器
    inTest = true;
    start () {
        this.touchEndEventScale(this.nodes.cancel, () => {
            this.curIndex = 10;
            this.calScore();
        })
        this.touchEndEventScale(this.nodes.addScore, () => {
          
        })
        //获取当前信息
        this.cardType = ccs.dataMgr.getCardById(this._args.id);
        this.leftTime = this.cardType.time;
        let tmp: questionType[] = ccs.dataMgr.getQuestionById(this.cardType.id);
        //随机题目
        while (this.item.length < this.cardType.count){
            var  temp = (Math.random()*tmp.length) >> 0;
            this.item.push(tmp.splice(temp,1)[0] as unknown as questionType);
        }
        //答案监听
        this.addAnswer();
        this.setQuestion();
    }
    setQuestion() {
        this.nodes.title.getComponent(cc.Label).string = this.cardType.name + "考试";
        this.nodes.question.getComponent(cc.RichText).string = this.item[this.curIndex].title;
        let str = '';
        this.nodes.answer.children.forEach((val, index) => {
            str = this.item[this.curIndex].options[index] + "";
            val.children[0].getComponent(cc.RichText).string = str.replace("&#10;", "")
        })
        this.nodes.leftCount.getComponent(cc.Label).string = "题目：" + (this.curIndex + 1) + "/" + this.cardType.count
    }
    addAnswer() {
        this.nodes.answer.children.forEach((val, index) => {
            this.touchEndEventScale(val, () => {
                if(this.curIndex > 9) {
                    return ;
                }
                //点哪个，查下是不是正确的答案
                if(index + 1 === this.item[this.curIndex].answer) {
                    this.score += 10;
                }
                this.curIndex ++;
                //下一题
                if(this.curIndex == 10) {
                    this.calScore();
                    return;
                }
                this.setQuestion();
            })
        })
    }
    closeWin(node: cc.Node) {
        node.scale = 2.5;
        cc.tween(node)
        .to(0.5, { opacity: 255, active: true})
        .to(0.5, { scale: 1})
        .start();                   
    }
    calScore() {

        game.gameMgr.saveGame();
        ccs.winMgr.showWin('popAlert', {content: "是否需要加分特权？", cb: () => {
                ccs.AD.showAd((c) => {
                    if(c) {
                        this.score += 10;
                        this.calCb(10);
                    } else {
                         this.calCb();
                    }
                })
            },
            cancel: () => {
                this.calCb();
            }
        })
        
    }
    calCb(cal?) {
        this.inTest = false; //更改考试状态
        this.nodes.score.getComponent(cc.Label).string = this.score.toString();
        this.closeWin(this.nodes.score);
        if(cal) {
            this.score += cal;
        }
        if(this.cardType.type == "edu") {
            //升学考试
            game.playerMgr.heroInfo.eduScore = this.score;
            game.recordMgr.addList({name: "你", action: `开始了${game.playerMgr.heroInfo.edu.name}升学考试`, location: "学校" });
        }else if(this.cardType.type == 'card' && this.score >= (this.cardType.score || 80)) {
            game.cardMgr.setCardState(this.cardType.id); //证书状态
            game.playerMgr.bag.cardBag.addItem(new cardBase(this.cardType));
            let test = game.playerMgr.heroInfo.works.find(val => val.id == this.cardType.id);
            if(test) {
                test.level += 1;
            }
            this.closeWin(this.nodes.pass);
            game.recordMgr.addList({action: `成绩出来了，你的成绩是${this.score}，恭喜通过了考试` });
        } else {
            this.closeWin(this.nodes.noPass);
            game.recordMgr.addList({action: `成绩出来了，你的成绩是${this.score}，恭喜未通过考试` });

        }
        this.nodes.ensure.active = false;
        this.nodes.cancel.active = false;
        this.nodes.btn_close.active = true;
        //增加下次考试时间
        game.cardMgr.setTime(this.cardType.id);
        ccs.mainEmitter.emit("refreshCard");
        game.gameMgr.saveGame();
        return;
    }
    update(dt) {
        this.timer += dt;
        if(this.timer >= 1 && this.inTest ) {
            this.nodes.time.getComponent(cc.Label).string = "倒计时：" + this.leftTime + "分钟";
            if(this.leftTime <= this.cardType.count) {
                this.nodes.time.color = cc.Color.RED;
            }
            this.timer = 0;
            this.leftTime --;
            if(this.leftTime <= 0) {
                //结束
                this.calScore();
                this.inTest = false;
            }
        }
    }
}
